//
//  AddDataVC.m
//  CoreDataLearn
//
//  Created by zhoutong on 17/4/13.
//  Copyright © 2017年 tong. All rights reserved.
//

#import "AddDataVC.h"
#import <UIViewController+MJPopupViewController.h>

#define CELLID @"addCVCellID"
//记录collectview开关状态
static BOOL collViewHiddenMode = NO;

@interface AddDataVC ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UITextFieldDelegate>
//储存图片集合
@property (nonatomic,strong) NSArray *imageArr;
//储存将要传输的字典数据
@property (nonatomic,strong) NSMutableDictionary *dataDic;
//用于回传数据的block
@property (nonatomic,copy) returnDataDic dataDicBlock;

@end

@implementation AddDataVC

- (void)dealloc{
    [self.headShowView removeFromSuperview];
    self.headShowView = nil;
}

- (NSArray *)imageArr{
    if (!_imageArr) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:5];
        for (int i = 0; i < 10; i++) {
            [arr addObject:[NSString stringWithFormat:@"0%d.png",i+1]];
        }
        _imageArr = [NSArray arrayWithArray:arr];
    }
    return _imageArr;
}

- (NSMutableDictionary *)dataDic{
    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionaryWithCapacity:5];
    }
    return _dataDic;
}

- (instancetype)initWithDataBlock:(returnDataDic)dataDicBlock{
    if (self = [super init]) {
        self.dataDicBlock = dataDicBlock;
    }
    return self;
}
- (void)fillData:(NSDictionary*)dic{
    self.headImge.image = [UIImage imageWithData:[dic objectForKey:@"headImage"]];
    self.nameField.text = [dic objectForKey:@"name"];
    self.ageField.text = [NSString stringWithFormat:@"%ld",[[dic objectForKey:@"age"] integerValue]];
    self.sexField.text = [[dic objectForKey:@"sex"] boolValue] ? @"男":@"女";
    
    self.dataDic = [NSMutableDictionary dictionaryWithDictionary:dic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //collection已经展示，但是默认给他隐藏
    collViewHiddenMode = NO;
    [self clickHeadImage];
    
//    self.headShowView.dataSource = self;
//    self.headShowView.delegate = self;
    
    [self.headShowView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CELLID];

    //给头像添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickHeadImage)];
    self.headImge.userInteractionEnabled = YES;
    [self.headImge addGestureRecognizer:tap];
    
    //给头像一个默认值
    [self.dataDic setObject:UIImagePNGRepresentation([UIImage imageNamed:@"01.png"]) forKey:@"headImage"];
}
- (IBAction)submitBtn:(id)sender {
    
    [self.nameField resignFirstResponder];
    [self.ageField resignFirstResponder];
    [self.sexField resignFirstResponder];
    
    if ([self.dataDic allValues].count != 4) {
        [self showHubMissingValue];
        return;
    }
    
    self.dataDicBlock(self.dataDic);
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}
//提示属性未填满
- (void)showHubMissingValue{
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    lab.backgroundColor = [UIColor grayColor];
    lab.center = self.view.center;
    lab.text = @"请完整添加数据";
    [self.view addSubview:lab];
    
    [UIView animateWithDuration:2 delay:2 options:nil animations:^{
        lab.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [lab removeFromSuperview];
    }];
}

- (void)clickHeadImage{
    collViewHiddenMode = !collViewHiddenMode;
    [self.headShowView setHidden:collViewHiddenMode];
}

#pragma mark-- collection代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID forIndexPath:indexPath];
//    cell.select
    
    CGFloat margin = 3;
    CGSize cellSize = cell.contentView.frame.size;
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(margin, margin, cellSize.width - margin*2, cellSize.height - margin*2)];
    img.image = [UIImage imageNamed:[self.imageArr objectAtIndex:indexPath.row]];
    img.tag = 13;
    img.layer.borderColor = [UIColor lightGrayColor].CGColor;
    img.layer.borderWidth = 2;
    
    [cell.contentView addSubview:img];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //先判断此次选中之前是否有选中的图片
    if ([self.dataDic objectForKey:@"headImage"]) {
        [self.dataDic removeObjectForKey:@"headImage"];
    }
    //把选中图片加入数组字典
    NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:[self.imageArr objectAtIndex:indexPath.row]]);
    [self.dataDic setObject:imageData forKey:@"headImage"];
    self.headImge.image = [UIImage imageWithData:imageData];
    [self.headShowView setHidden:YES];
}
#pragma mark -- UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{}
  //编辑完毕，准备提交
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //先隐藏头像选择界面
    collViewHiddenMode = NO;
    [self clickHeadImage];
    //判断输入不为空   TODO:可以再判断数据是否重复输入的
    if ([textField.text length] == 0) {
        return;
    }
    //判断数据字典情况
    if (textField == self.nameField) {
        [self.dataDic removeObjectForKey:@"name"];
        [self.dataDic setObject:textField.text forKey:@"name"];
        
    }else if (textField == self.ageField) {
        [self.dataDic removeObjectForKey:@"age"];
        [self.dataDic setObject:[NSNumber numberWithInt:[textField.text intValue]] forKey:@"age"];
        
    }else if (textField == self.sexField) {
        [self.dataDic removeObjectForKey:@"sex"];
        BOOL sex = [textField.text isEqualToString:@"男"];
        [self.dataDic setObject:[NSNumber numberWithBool:sex] forKey:@"sex"];
    }
    
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    return NO;
//}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}

@end
